package com.earl.gsm.service.impl.security;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.earl.gsm.commons.dao.BaseDao;
import com.earl.gsm.commons.service.BaseServiceImpl;
import com.earl.gsm.dao.RoleDao;
import com.earl.gsm.dao.UserDao;
import com.earl.gsm.dao.UserRoleDao;
import com.earl.gsm.domain.sercurity.role.Role;
import com.earl.gsm.domain.sercurity.user.User;
import com.earl.gsm.domain.sercurity.user.UserQuery;
import com.earl.gsm.domain.sercurity.userrole.UserRole;
import com.earl.gsm.service.UserService;

@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User, UserQuery>
        implements UserService {

    private static Logger logger = Logger.getLogger(UserServiceImpl.class);

    @Resource
    private UserDao dao;
    
    @Resource
    private UserRoleDao urDao;

    @Resource
    private RoleDao roleDao;

    @Override
    protected BaseDao<User> getDao() {
        return dao;
    }

    @Override
    public List<Role> findRole(Long userId) {
    	
    	UserRole ur = new UserRole();
    	ur.setUserId(userId);
    	List<UserRole> urList =  urDao.searchQuery(ur);
    	List<Long> tmp = new ArrayList<Long>();
    	for (UserRole userRole : urList) {
    		tmp.add(userRole.getRoleId());
		}
    	return roleDao.findByList(tmp);
    }

    @Override
    public void deleteCascade(Long userId) {

    }

    @Override
    public void doLogin(String username, String password) {

    }

    @Override
    public List<String> findRoleName(Long l) {
        return null;
    }

    @Override
    public List<String> findPrivilegeCode(long l) {
        return null;
    }

    @Override
    public Boolean saveUser(User user) {
        return null;
    }

	@Override
	public void addUserInfo(User user, Integer[] roleId) {
		// TODO Auto-generated method stub
		Integer userId = dao.insertBackId(user);
		updateRole(userId.longValue(), roleId);
		
	}
	
	public void updateRole(Long userId,Integer[] privilegeId){
		UserRole rpQuery = new UserRole();
		rpQuery.setRoleId(userId);
		urDao.deleteByQuery(rpQuery);
		for (Integer integer : privilegeId) {
			UserRole ur = new UserRole();
			ur.setUserId(userId);
			ur.setRoleId(integer.longValue());
			urDao.insert(ur);
		}
	}

	@Override
	public void updateUserInfo(User user, Integer[] roleId) {
		// TODO Auto-generated method stub
		dao.updateByPrimaryKeySelective(user);
		updateRole(user.getId(), roleId);
	}
}
